package com.qiche.service.impl;

import java.util.List;

import com.qiche.aspect.Result;
import com.qiche.dto.ProductWithStagesDto;
import com.qiche.enums.ResultEnum;
import com.qiche.mapper.ProductCategoryMapper;
import com.qiche.mapper.WorkstageMapper;
import com.qiche.model.Product;
import com.qiche.model.Workstage;
import com.qiche.util.UserUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qiche.model.User;
import com.qiche.service.ProductService;

import tk.mybatis.mapper.entity.Example;

/**
 * Created by Linzw on 2018/01/24.
 */
@Service("productService")
public class ProductServiceImpl extends BaseService<Product> implements ProductService {


    @Autowired
    private ProductCategoryMapper categoryMapper;
    @Autowired
    private WorkstageMapper workstageMapper;

    @Override
    public PageInfo<Product> selectByPage(Product product, int page, int limit) {
        Example example = new Example(Product.class);
        Example.Criteria criteria = example.createCriteria();
        // 分页查询
        if (product.getMerchantId() != null && product.getMerchantId() != 0) {
            criteria.andEqualTo("merchantId", product.getMerchantId());
        }
        if (product.getName() != null && !"".equals(product.getName())) {
            criteria.andLike("name", "%" + product.getName() + "%");
        }
        if (product.getCategoryId() != null && !"".equals(product.getCategoryId() + "")) {
            criteria.andEqualTo("categoryId", product.getCategoryId());
        }
        PageHelper.startPage(page, limit);
        List<Product> productList = selectByExample(example);
        return new PageInfo<>(productList);
    }

    @Override
    public Product selectById(Long regionId) {
        Example example = new Example(Product.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("id", regionId);
        List<Product> regionList = selectByExample(example);
        if (regionList.size() > 0) {
            return regionList.get(0);
        }
        return null;
    }

    @Override
    public List<Product> selectByCate(Long cateId) {

        User currentUser = (User) SecurityUtils.getSubject().getPrincipal();

        Example example = new Example(Product.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("categoryId", cateId);
        criteria.andEqualTo("merchantId", currentUser.getMerchantId());
        List<Product> productList = selectByExample(example);
        return productList;
    }

    @Override
    public List<Product> selectByRegion(Long regionId) {
        Example example = new Example(Product.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("regionId", regionId);
        List<Product> regionList = selectByExample(example);
        return regionList;
    }

    @Override
    public List<Product> selectByMerchantId(Long merchantId) {
        Example example = new Example(Product.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("merchantId", merchantId);
        criteria.andIsNull("regionId");
        return selectByExample(example);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = {Exception.class})
    public Result delProduct(Long productId) {
        try {
            int deleteCount = mapper.deleteByPrimaryKey(productId);
            if (deleteCount == 0) {
                return Result.createByErrorMessage("删除失败");
            }
        } catch (DataIntegrityViolationException e) {
            e.printStackTrace();
            return Result.createByResultEnum(ResultEnum.PRODUCT_HAS_RELATIVED);
        }
        return Result.createBySuccessMessage("删除成功");

    }

    @Transactional
    @Override
    public Result addOrUpdateProduct(ProductWithStagesDto pwsDto) {
        User currentUser = UserUtils.getCurrentUser();
        Product product =new Product();

        product.setCategoryId(pwsDto.getCategoryId().longValue());
        product.setCategoryName(categoryMapper.selectByPrimaryKey(pwsDto.getCategoryId()).getName());
        product.setMerchantId(currentUser.getMerchantId().longValue());
        product.setName(pwsDto.getName());
        product.setConsumeTime(pwsDto.getConsumeTime());
        product.setPrice(pwsDto.getPrice());
        product.setProcedureCount(pwsDto.getWorkstageList().size());
        product.setDescription(pwsDto.getDescription());

        if (pwsDto.getId() == null) {
            mapper.insert(product);
        } else {
            product.setId(pwsDto.getId().longValue());
            mapper.updateByPrimaryKey(product);
        }

        if(pwsDto.getToDeteleWsIds()!=null &&!pwsDto.getToDeteleWsIds().isEmpty()){
            Example example=new Example(Workstage.class);
            Example.Criteria criteria=example.createCriteria();
            criteria.andIn("id",pwsDto.getToDeteleWsIds());
            workstageMapper.deleteByExample(example);
        }
        if (pwsDto.getWorkstageList()!=null &&!pwsDto.getWorkstageList().isEmpty()) {
            for (Workstage tempWorkStage : pwsDto.getWorkstageList()) {
                if (tempWorkStage.getId() == null) {
                    tempWorkStage.setItemId(product.getId());
                    workstageMapper.insert(tempWorkStage);
                } else {
                    workstageMapper.updateByPrimaryKey(tempWorkStage);
                }
            }
        }
        return Result.createBySuccessMessage("添加成功");
    }

}




